package com.example.selectdorm.controller;

import com.example.selectdorm.dto.OrderDTO;
import com.example.selectdorm.dto.StudentIdAndAuthCode;
import com.example.selectdorm.entity.*;
import com.example.selectdorm.service.*;
import com.example.selectdorm.vo.ResultVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/order")
public class OrderController {

    private final DormitoryBuildingService dormitoryBuildingService;
    private final OrderService orderService;
    private final UserAuthCodeService userAuthCodeService;
    private final UserInfoService userInfoService;
    private final CheckInService checkInService;
    private final OrderInfoService orderInfoService;

    @GetMapping("/hello")
    public String hello(){
        return "hello, here in select dorm";
    }

    @PostMapping("/order")
    public ResultVO takeOrder(@RequestBody OrderDTO orderDTO) {
//       生成订单信息
        String studentId = orderDTO.getStudentId();
        String buildingName = orderDTO.getBuildingName();
        List<StudentIdAndAuthCode> roommates = orderDTO.getRoommates();

        UserInfo userInfo = userInfoService.getByStudentId(studentId);
        Long uid = userInfo.getId();
        Long buildingId = dormitoryBuildingService.findBuildingByName(buildingName).get().getId();
        String gender = userInfo.getGender();
        int totalCount = 1 + roommates.size();
        Date orderTime = new Date();

        if(checkInService.isCheckedIn(uid)) {
            return new ResultVO(400, "已选宿舍");
        }

        Order order = new Order(uid, buildingId, gender, totalCount, false, orderTime);
        orderService.createOrder(order);

        List<UserInfo> actualRoommates = new ArrayList<>();


//      校验 auth code 以及性别
//      TODO: 用户重复以及没有该用户的异常，用户已经选过宿舍
        for (StudentIdAndAuthCode roommate: roommates) {
            UserInfo roommateInfo = userInfoService.getByStudentId(roommate.getStudentId());
            actualRoommates.add(roommateInfo);
            Long roommateUid = roommateInfo.getId();

            if(!userAuthCodeService.verifyUserAuthCode(roommateUid, roommate.getAuthCode())
                    || !roommateInfo.getGender().equals(gender)
                    || checkInService.isCheckedIn(roommateUid)) {
                return new ResultVO(400, "校验不通过");
            };
        }

//        查找符合条件的宿舍
        List<DormitoryRoom> rooms = dormitoryBuildingService.orderRoom(buildingId, gender, totalCount);

//        随机选一个宿舍
        DormitoryRoom selectedRoom = rooms.get((int) (Math.random() * rooms.size()));
        selectedRoom.setRestBeds(selectedRoom.getRestBeds() - totalCount);

//        创建用户宿舍关联信息表
//        TODO : 创建多条关联信息
        CheckIn checkIn = new CheckIn(uid, selectedRoom.getId(), new Date().toString(), true);
        checkInService.addCheckIn(checkIn);

        String roommateIds = "";

        for(UserInfo roommate: actualRoommates) {
            roommateIds = roommateIds.concat(" " + roommate.getId().toString());
            CheckIn checkInRoommate = new CheckIn(roommate.getId(), selectedRoom.getId(), new Date().toString(), true);
            checkInService.addCheckIn(checkInRoommate);
        }

//        创建订单详情表
        OrderInfo orderInfo = new OrderInfo(order.getId(), roommateIds);
        orderInfoService.addOrderInfo(orderInfo);

//        修改 order 状态
        order.setSuccess(true);
        orderService.updateOrder(order);

        return new ResultVO(200, "success", order);
    }
}
